// initSession_ID();// 初始化session_id
var skusparams = {};
//初始化完成自动执行s
$(document).ready(function () {
    //入口判断   isShare分享页进入，coupon_params优惠券跳转进入 ， machCode扫码进入
    var path = "/news/list";
    skusparams.machCode = machCode; //机器码
    //获取公司ID
    getCompanyId();
    //入口判断
    if(machCode) {
        skusparams.machCode = machCode;
    }
//====================++++++++++++++初始化STORE_ID 、SESSION_ID 后callback调用需要用到STORE_ID 、SESSION_ID 的程序+++++++++++++++======================
        //获取顶部轮播图广告列表
        var newsPath = "ad/list";
        var newsParams = {
            "STORE_ID":STORE_ID,
            "EN_NAME":"home_top_banner",
            "PAGE_CAPACITY":10,
            "PAGE_INDEX":1
        };
        request(newsPath,newsParams,function (res) {
            var domStr =
                '<a class="sw-slide" href="%s">\
                     <img src="%s" alt="Summer beach concept">\
                </a>';
            if(res.BODY && res.BODY.LIST && res.BODY.LIST.length > 0) {
                $("#sliders").empty();
                _.each(res.BODY.LIST,function (item, index) {
                    $("#sliders").append(sprintf(domStr,item.PIC_GOTO,item.PIC_URL));
                });
                var len = res.BODY.LIST.length - 1;
                $("#sliders").prepend(sprintf(domStr,res.BODY.LIST[len].PIC_GOTO,res.BODY.LIST[len].PIC_URL));
                $("#sliders").append(sprintf(domStr,res.BODY.LIST[0].PIC_GOTO,res.BODY.LIST[0].PIC_URL));
            }
        })

        //获取某店铺下类别及商品
        var storeCategPath = "store/catalog";
        var categParams = {
            "STORE_ID":STORE_ID
        }
        request(storeCategPath,categParams,function (res) {
            var categs_id = res.BODY.LIST;
            var skusPath = "store/skus";
            var CategName = "";
            var sortList =  categs_id.sort( function(a,b){
                return a.CATALOG_ID > b.CATALOG_ID;
            });
            var categListDom = $(".categ-ul");
            categListDom.empty();
            var categItemDom = '<li><a class="%s" fl="%s">%s<span id="fl%s" class="floor-num">3</span></a></li>';
            var categContaner = $(".categ-prod-cont")
            categContaner.empty();
            var categContainerItem = '<div class="" id="floor%s">\
                                   <div class="catag-seprate">%s</div>\
                                   <div class="prods">\
                                   </div>\
                               </div>';
            for(let i = 0;i< sortList.length;i++) {
                (function () {
                    var activecateg = i == 0 ? "categ-active" : "";
                    categListDom.append(sprintf(categItemDom,activecateg,i+1,sortList[i].NAME,i+1));
                    categContaner.append(sprintf(categContainerItem,i+1,sortList[i].NAME));
                    // CategName = "#floor" + (i+1);
                    var skusParams = {
                        "STORE_ID":STORE_ID,
                        "CATALOG_ID":sortList[i].CATALOG_ID
                    };
                    request(skusPath,skusParams,getCoffeeList,i);
                })(i);
            }
        });

});
//初始化完成自动执行e

//获取咖啡列表
function getCoffeeList(res,i) {
    var str =
        '<div class="prod-item">\
            <div class="prod-img">\
                <img src="%s" alt="">\
            </div>\
            <div class="prod-info">\
                <div class="prod-name">%s</div>\
                <div class="price-operate price-selector">\
                    <div class="price red-text"><span>￥</span><span class="sell-price">%s</span><s class="origin-price">%s</s></div>\
                    <div class="add-reduce prod-operate" sku_id="%s" spu_id="%s">\
                        <a class="add-subtract" flg="substrat">-</a><span class="prod-num"></span><a class="add-subtract" flg="add">+</a>\
                    </div>\
                </div>\
            </div>\
        </div>';
    if(res.BODY) {
        var count = 0;
        _.each(res.BODY.LIST,function (item,index) {
            count = index;
            var product = sprintf(str,item.BIG_PIC,item.NAME,item.SALE_PRICE.toFixed(2),item.LIST_PRICE.toFixed(2),item.SKU_ID,item.SPU_ID);
            $("#floor" + (i+1)).append(product);
        });
    }
}
//添加购物车
$(".categ-ul").on("tap","li a",function (e) {
    var fl = Number($(e.currentTarget).attr("fl"));
    var scrollHeight = 0;
    for(var i = 1;i < fl; i++) {
        scrollHeight += $("#floor" + i).height();
    }
    $(".product-contenner").animate({scrollTop:scrollHeight} ,500);
});
$(".product-contenner").on("scroll",function (e) {
    var scrollTop = $(e.currentTarget).scrollTop();
    var categNum = $(".categ-ul li").length;
    var prodItemH = 0;
    for(var i = 1;i <= categNum; i++) {
        prodItemH +=  $("#floor" + i).height();
        if(scrollTop<= 80) {
            $(".categ-ul li a").removeClass("categ-active");
            $($(".categ-ul li")[0]).children("a").addClass("categ-active");
        } else if(scrollTop >= prodItemH - 80) {
            $(".categ-ul li a").removeClass("categ-active");
            $($(".categ-ul li")[i]).children("a").addClass("categ-active");
        }
    }
})
$("#home_page").on("click",".add-subtract",function (e) {
    var cartPanelItem = '<div class="selected-item">\
             <div class="sel-prod-name">%s</div>\
             <div class="select-item-r price-selector">\
                 <div class="price red-text"><span>￥</span><span class="sell-price">%s</span><s style="display: none;" class="origin-price">%s</s></div>\
                 <div class="add-reduce panel-operate" sku_id="%s" spu_id="%s">\
                     <a class="add-subtract" flg="substrat">-</a><span class="prod-num">1</span><a class="add-subtract" flg="add">+</a>\
                 </div>\
             </div>\
         </div>';
    var thisParentDom = $(e.currentTarget).parent(".add-reduce");
    var thisNumDom = thisParentDom.children(".prod-num");
    var thisNum = Number(thisNumDom.text());
    var cartNum = Number($("#cartNum").text());
    var flg = $(e.currentTarget).attr("flg");
    var realAmountDom = $("#realAmount");
    var originAmountDom = $("#originAmount");
    var realAmount = Number(realAmountDom.text());
    var originAmount = Number(originAmountDom.text());
    var prodinfoDom = $(e.currentTarget).parents(".price-selector");
    var sellPrice = Number(prodinfoDom.find(".sell-price").text());
    var originPrice = Number(prodinfoDom.find(".origin-price").text());
    var sku_id = thisParentDom.attr("sku_id");
    var spu_id = thisParentDom.attr("spu_id");
    var addReduceDom = $(".add-reduce[sku_id="+sku_id+"]"); //thisParentDom 是其中的一个
    var accountDom = $("#account");
    if(flg == "add") {
        thisNum++
        cartNum++;
        realAmount += sellPrice;
        originAmount += originPrice;
        $(thisParentDom.find("a")[0]).css("display","inline-block");
        $("#cartNum").css("display","inline-block");
        $(".total-amount").css("display","inline-block");
        thisNumDom.css("display","inline-block");
        accountDom.css("display","inline-block");
        if(thisNum == 1) {
            var prodName = $(e.currentTarget).parents(".prod-info").find(".prod-name").text();
            $(".c-panel-contaner").prepend(sprintf(cartPanelItem,prodName,sellPrice.toFixed(2),originPrice.toFixed(2),sku_id,spu_id));
        }
    } else {
        if(thisNum > 0) {
            thisNum--
        }
        if(thisNum <= 0) {
            $(addReduceDom.find("a")[0]).css("display","none");
            thisNum = 0;
            addReduceDom.children(".prod-num").css("display","none");
            $(".add-reduce[sku_id="+sku_id+"]").parents(".selected-item").remove();
        }
        if(cartNum > 0) {
            cartNum--
        }
        if(cartNum <= 0){
            $("#cartNum").css("display","none");
            $(".total-amount").css("display","none");
            accountDom.css("display","none");
            $(".cart-mask").css("display","none");
            $(".addprods-panel").css("display","none");
            $("#account").text("结算")
        };
        realAmount -= sellPrice;
        originAmount -= originPrice;
    }
    addReduceDom.find(".prod-num").text(thisNum)
    // thisNumDom.text(thisNum.toFixed(0));
    $("#cartNum").text(cartNum.toFixed(0));
    $($(".panel-title span")[1]).text(cartNum.toFixed(0));
    realAmountDom.text(realAmount.toFixed(2));
    originAmountDom.text(originAmount.toFixed(2));
});
$(".cart").on("tap",function (e) {
    var hasSelected =$(".c-panel-contaner").find(".selected-item").length;
    if(hasSelected) {
        $(".cart-mask").css("display","block");
        $(".addprods-panel").css("display","block");
        $("#account").text("购买")
    }
});
$(".close-model").on("tap",function (e) {
    $(".cart-mask").css("display","none");
    $(".addprods-panel").css("display","none");
    $("#account").text("结算")
    e.stopPropagation();
    e.preventDefault();
})
$("#account").on("tap",function (e) {
    if($(e.currentTarget).text() == "购买") {
        var SKU_LIST = [];
        var skuDomList = $(".selected-item").find(".panel-operate");
        _.each(skuDomList,function (item, index) {
            var SKU_ID = $(item).attr("sku_id");
            var SKU_NUM = Number($(item).find(".prod-num").text());
            // var SPU_ID = $(item).attr("spu_id");
            SKU_LIST.push({
            "SKU_ID":SKU_ID,
            "SKU_NUM":SKU_NUM,
            "STYPE": 4
            })
        });
        skusparams.SKU_LIST = SKU_LIST;
        skusparams.totalFee = Number($("#realAmount").text());
        sessionStorage.setItem("skusparams",JSON.stringify(skusparams));
        var url = "./order_detail.html";
        location.href = (url);
    }
})